const NewsService = require("../../services/admin/NewsService")




const NewsController = {
    add: async (req, res) => {
        try {
            // console.log(req.file, req.body);
            // 封面获取，如果不存在则为空
            const cover = req.file ? `/newsuploads/${req.file.filename}` : ""
            const { title, content, category, publish, author } = req.body
            await NewsService.add({ title, content, author, category: Number(category), publish: Number(publish), cover, editTime: new Date() })
            res.send({
                ActionType: "OK"
            })
        } catch (error) {
            res.send({ errorMsg: "添加新闻失败，新闻已存在" });
        }


    },
    update: async (req, res) => {
        try {
            // console.log(req.file, req.body);
            // 封面获取，如果不存在则为空
            const cover = req.file ? `/newsuploads/${req.file.filename}` : ""
            const { _id, title, content, category, publish } = req.body
            await NewsService.update({ _id, title, content, category: Number(category), publish: Number(publish), cover, editTime: new Date() })
            res.send({
                ActionType: "OK"
            })
        } catch (error) {
            res.send({ errorMsg: "更新新闻失败" });
        }

    },
    // 首次获取新闻，只有你是作者的时候才显示你的新闻数据
    getListByAuthor: async (req, res) => {
        try {
            const result = await NewsService.getListByAuthor({ author: req.params.author })
            // console.log(result);
            res.send({
                ActionType: "OK",
                data: result
            })
        } catch (error) {
            res.send({ errorMsg: "查询新闻失败" });
        }
    },
    // 编辑新闻时候，根据id获取到对应的新闻
    getListById: async (req, res) => {
        try {
            // console.log(req.params);
            const result = await NewsService.getListById({ _id: req.params.id })
            // console.log(result);
            res.send({
                ActionType: "OK",
                data: result
            })

        } catch (error) {
            res.send({ errorMsg: "查询新闻失败" });
        }
    },
    publish: async (req, res) => {
        try {
            await NewsService.publish({ ...req.body, editTime: new Date() })
            res.send({
                ActionType: "OK"
            })
        } catch (error) {
            res.send({ errorMsg: "更新新闻发布状态失败" });

        }
    },
    delete: async (req, res) => {
        try {
            await NewsService.delete({ _id: req.params.id })
            res.send({
                ActionType: "OK"
            })
        } catch (error) {
            res.send({ errorMsg: "删除新闻失败" })
        }
    }
}


module.exports = NewsController